package com.aiju.cash.ui.main.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.aiju.base.fragment.BaseTitleFragment;
import com.aiju.cash.R;
import com.aiju.cash.core.api.BlotterApi;
import com.aiju.cash.core.api.DataJson;
import com.aiju.cash.core.event.BlotterEvent;
import com.aiju.cash.ui.good.adapter.TeamsAndHeaderAdapter;
import com.aiju.cash.ui.main.BlotterInfoActvity;
import com.aiju.cash.ui.main.BlotterSelectActivity;
import com.aiju.cash.ui.main.adapter.BlotterAdater;
import com.aiju.cash.ui.main.entity.BlotterList;
import com.aiju.common.event.EventBusHandler;
import com.aiju.common.event.EventCenter;
import com.aiju.support.recyclerView.DividerItemDecoration;
import com.aiju.utils.L;
import com.aiju.utils.T;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.chanven.lib.cptr.loadmore.SwipeRefreshHelper;
import com.chanven.lib.cptr.recyclerview.RecyclerAdapterWithHF;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * @author: 佐为
 * @date: 2016-11-15 11:06
 * @version: V1.0
 * @Description: 流水
 */
public class BlotterFragment extends BaseTitleFragment {

    private int currentNum = 1;
    private int pageSize = 10;
    private View empty;
    private RecyclerView recyclerviewTeams;
    private LinearLayoutManager mTeamsLayoutManager;
    private BlotterAdater mBlotterAdater;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private SwipeRefreshHelper mSwipeRefreshHelper;
    private RecyclerAdapterWithHF mAdapter;
    private BlotterApi mBlotterApi;
    private boolean isLoad;

    private boolean isRefresh;

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_blotter, container, false);
        initView(inflate);
        return inflate;
    }

    private void initView(View root) {
        setCenterTitle("流水");
        if ("2".equals(mUser.getRole())) {
            mAiJuTitleBarView.setRightTitle("");
        } else {
            mAiJuTitleBarView.setRightTitle("统计");
        }
        empty = root.findViewById(R.id.iv_empty);
        recyclerviewTeams = (RecyclerView) root.findViewById(R.id.recyclerview_teams);
        mTeamsLayoutManager = new LinearLayoutManager(getActivity());
        recyclerviewTeams.setLayoutManager(mTeamsLayoutManager);
        recyclerviewTeams.addItemDecoration(new DividerItemDecoration(getActivity(),
                DividerItemDecoration.VERTICAL_LIST));
        mSwipeRefreshLayout = (SwipeRefreshLayout) root.findViewById(R.id.sryt_swipe_listview);
        mSwipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.app_title_color));
        mSwipeRefreshHelper = new SwipeRefreshHelper(mSwipeRefreshLayout);
        mSwipeRefreshHelper.setOnSwipeRefreshListener(new SwipeRefreshHelper.OnSwipeRefreshListener() {
            @Override
            public void onfresh() {
                L.d("onfresh");
                isRefresh = true;
                currentNum = 1;
                map.clear();
                getBlotterList();
            }
        });
        mSwipeRefreshHelper.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                if (mSwipeRefreshLayout.isRefreshing()) {
                    mSwipeRefreshHelper.loadMoreComplete(true);
                    return;
                }
                L.d("loadMore");
                isLoad = true;
                ++currentNum;
                getBlotterList();
            }
        });
        mAiJuTitleBarView.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(BlotterSelectActivity.class);
            }
        });
        mBlotterApi = new BlotterApi();
        getBlotterList();

        EventCenter.bindContainerAndHandler(getLifecycle(), new EventBusHandler() {
            public void onEventMainThread(BlotterEvent event) {
                mAiJuTitleBarView.post(new Runnable() {
                    @Override
                    public void run() {
                        L.d("BlotterFragment：BlotterEvent");
                        mSwipeRefreshHelper.autoRefresh();
                    }
                });
            }
        }).tryToRegisterIfNot();
    }

    @Override
    protected boolean enableDefaultBack() {
        return false;
    }

    private void getBlotterList() {
        mDialogHelper.showLoadingProgressDialog();
        L.d("当前页：" + String.valueOf(currentNum));
        String operatorId = "";
        if (!mUser.isAdmin()) {
            operatorId = mUser.getOperatorId();
        }
        mBlotterApi.queryDealStatistics(mUser, "", mUser.getOperatorId(), "nearly7",
                "支付宝，微信，现金，二维码台卡", "1,2", String.valueOf(currentNum), String.valueOf(pageSize), new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        mDialogHelper.dismissProgressDialog();
                        T.ToastNetError();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        mDialogHelper.dismissProgressDialog();
                        DataJson json = new DataJson(response);
                        if (json.isSuccess()) {
                            if ("null".equals(json.getData().toString())) {
                                empty.setVisibility(View.VISIBLE);
                                recyclerviewTeams.setVisibility(View.GONE);
                                return;
                            }
                            List<BlotterList> list = new Gson().fromJson(json.getData().toString(), new TypeToken<List<BlotterList>>() {
                            }.getType());
                            setBlotterListView(list);
                        } else {
                            T.ToastShort(json.getMsg());
                        }
                    }
                });
    }

    List<BlotterList> blotterLists = new ArrayList<>();
    Map<String, BlotterList> map = new HashMap<>();

    /**
     * 处理数据
     */
    private void soreData() {
        Object[] key = map.keySet().toArray();
        Arrays.sort(key);
        for (int i = 0; i < key.length; i++) {
            blotterLists.add(map.get(key[i]));
        }
        Collections.reverse(blotterLists);
    }

    private void setBlotterListView(List<BlotterList> list) {
        for (BlotterList blotter : list) {
            BlotterList blotterList = map.get(blotter.getDate());
            if (blotterList != null) {
                blotterList.getList().addAll(blotter.getList());
            } else {
                map.put(blotter.getDate(), blotter);
            }
        }
        if (mAdapter == null) {
            soreData();
            mBlotterAdater = new BlotterAdater(getActivity(), blotterLists);
            mAdapter = new RecyclerAdapterWithHF(mBlotterAdater);
            recyclerviewTeams.setVisibility(View.VISIBLE);
            recyclerviewTeams.setAdapter(mAdapter);
            final StickyRecyclerHeadersDecoration headersDecor = new StickyRecyclerHeadersDecoration(mBlotterAdater);
            recyclerviewTeams.addItemDecoration(headersDecor);
            mBlotterAdater.setOnItemClickListener(new TeamsAndHeaderAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    Intent intent = new Intent(getActivity(), BlotterInfoActvity.class);
                    intent.putExtra("id", mBlotterAdater.getTeamList().get(position).getId());
                    intent.putExtra("title", mBlotterAdater.getTeamList().get(position).getReceTypeDesc());
                    startActivity(intent);
                }
            });
        } else {
            blotterLists.clear();
            soreData();
            mBlotterAdater.setCategoryList(blotterLists);
        }
        completeView(list);
    }

    /**
     * 加载完成视图动作
     *
     * @param blotterLists
     */
    private void completeView(List<BlotterList> blotterLists) {
        //加载
        if (isLoad) {
            isLoad = false;
            mSwipeRefreshHelper.loadMoreComplete(true);
        }
        //刷新
        if (isRefresh) {
            isRefresh = false;
            mSwipeRefreshHelper.refreshComplete();
            mSwipeRefreshHelper.setLoadMoreEnable(true);
        }

        if (getDataSize(blotterLists) < pageSize) {
            mSwipeRefreshHelper.setLoadMoreEnable(false);
        } else {
            mSwipeRefreshHelper.setLoadMoreEnable(true);
        }
        checkIfEmpty();
    }

    private void checkIfEmpty() {
        if (mBlotterAdater != null && mSwipeRefreshHelper != null) {
            final boolean emptyViewVisible = mBlotterAdater.getItemCount() == 0;
            if (emptyViewVisible) {
                //T.ToastShort("没有相关数据");
                empty.setVisibility(View.VISIBLE);
                recyclerviewTeams.setVisibility(View.GONE);
            } else {
                empty.setVisibility(View.GONE);
                recyclerviewTeams.setVisibility(View.VISIBLE);
            }
        }
    }

    private int getDataSize(List<BlotterList> blotterLists) {
        int size = 0;
        for (BlotterList blotterList : blotterLists) {
            size += blotterList.getList().size();
        }
        return size;
    }
}
